import {
    //refresh,
    //refreshByID,
    //removeItem,
    //updateItem,
    //newItem,
    get,
    getAll,
    update,
    getEx,
    rawGet,
} from '@/services/crud'
import { getOnlineState } from '@/services/state'
var moment = require('moment');
moment.defaultFormat = "YYYY-MM-DD HH:mm:ss";
//import Vue from 'vue'
function getChildren(re, rej, parentId, commit) {
    get("station", "condition?stations.parent_id=" + parentId).then((resdev) => {
        if (resdev && resdev.data && resdev.data.result) {
            commit('setChildStation', { parentId, children: resdev.data.result })
        }
        rawGet("api/extend/api/m_smartBoxForPolice?qmap[ctype]=thing_ex & qmap[station_id]=" + parentId).then(res => {
            if (res && res.data && res.data.result) {
                commit('setThing', { parentId, things: res.data.result })
            }
            re()
        }).catch(err => rej(err))
    }).catch(err => rej(err))
}

export default {
    namespaced: true,
    state: {
        stationTree: [],
        treeFiltered: [],
        stationCache: {},
        thingCache: {},
        modelCache: {},
        edges: [],
        activeThing: {},

    },
    getters: {
        stationTree: state => {
            return state.stationTree
        },
        thingCache: state => {
            return state.thingCache
        },
        treeFiltered: state => {
            return state.treeFiltered
        }
    },
    mutations: {
        setModels(state, models) {
            if (models) {
                models.forEach(m => {
                    state.modelCache[m.uid] = m
                    if (typeof m.body == 'string') {
                        m.obody = JSON.parse(m.body)
                    }
                })
            }
        },
        setEdges(state, edges) {
            state.edges = edges
        },
        setChildStation(state, { parentId, children }) {
            //console.log("**********", rootState)
            if (children) {
                children.sort((a, b) => {
                    return a.s_name < b.s_name
                })

                children.forEach(c => {
                    c.name = c.s_name
                    c.label = c.s_name
                    c.id = c.uid
                    state.stationCache[c.uid] = c
                    c.model = state.modelCache[c.model_id]
                    if (c.model) {
                        c.isLeaf = !c.model.is_station
                    }
                })
                let tree = []
                children.forEach(c => {

                    if (!c.parent_id) {
                        tree.push(c)
                    } else {
                        let p = state.stationCache[c.parent_id]
                        if (p) {
                            if (!p.children) {
                                p.children = []
                                p.children2 = new Set
                            }
                            if (!p.children2.has(c.uid)) {
                                p.children.push(c)
                                p.children2.add(c.uid)

                            }

                        }
                    }
                })

                if (parentId === "") {
                    state.stationTree = tree

                } else {
                    let p = state.stationCache[parentId]
                    if (p) {
                        p.children = tree
                    }
                }

            }
        },
        setThing(state, { parentId, things }) {
            //console.log("**********", rootState)
            if (things) {
                things.sort((a, b) => {
                    return a.s_name < b.s_name
                })
                things.forEach(t => {
                    t.name = t.s_name
                    t.name_ip = t.s_name
                    if (t.ip) {
                        t.name_ip += ("@" + t.ip)
                    }
                    t.id = t.uid
                    t.data = t
                })

                let p = state.stationCache[parentId]
                if (p) {
                    p.children = []
                    things.forEach(t => {
                        t.type = 'obj'
                        t.isLeaf = true
                        state.thingCache[t.uid] = t
                        p.children.push(t)
                        t.model = state.modelCache[t.model_id]
                        if (t.model) {
                            t.isLeaf = !t.model.is_station
                        }
                    });
                }
            }
            state.stationTree = [...state.stationTree]
        },
        setThings(state, { res, filterFun }) {
            let things = res
            if (things && Array.isArray(things)) {
                let cache = {}
                let stationtree = []
                if (filterFun) {
                    things = things.filter(t => {
                        if (t.is_station) {
                            return true
                        }
                        return filterFun(t)
                    })
                }
                things.forEach(t => {
                    t.key = t.uid
                    t.name = t.s_name
                    t.label = t.s_name
                    t.id = t.uid
                    t.data = t
                    cache[t.uid] = t
                    t.name_ip = t.s_name
                    if (t.ip) {
                        t.name_ip += ("@" + t.ip)
                    }

                })
                var first
                things.forEach(t => {
                    if (!t.is_station) {
                        let station = cache[t.station_id]
                        if (station) {
                            if (!station.children) {
                                station.children = []
                            }
                            station.children.push(t)
                            t.parent = station
                            if (t.model_id == 'm_smartBoxForPolice') {
                                first = t
                            }

                        }
                    } else {

                        if (t.parent_id == "" || t.parent_id == undefined || t.parent_id == null ||
                            t.parent_id == 'null') {
                            stationtree.push(t)
                            if (!t.children) {
                                t.children = []
                            }
                        } else {
                            let parent = cache[t.parent_id]
                            if (parent) {
                                if (!parent.children) {
                                    parent.children = []
                                }
                                parent.children.push(t)
                                t.parent = parent
                            }
                        }
                    }
                })
                for (let item in cache) {
                    let t = cache[item]

                    if (t.is_station) {
                        continue
                    }
                    if (t.box_id) {
                        let box = cache[t.box_id]
                        if (box) {
                            if (!box.cameras) {
                                box.cameras = []
                            }
                            box.cameras.push(t)
                            continue
                        }
                    }
                    let parent = t.parent
                    if (!t.position) {
                        t.position = [t.s_name]
                    }
                    while (parent) {

                        t.position.unshift(parent.s_name)
                        if (parent == parent.parent) {
                            parent.parent = undefined

                        }
                        parent = parent.parent
                    }
                    //console.log(t.position)
                }
                state.thingCache = cache
                if (filterFun) {
                    state.treeFiltered = stationtree
                } else {
                    state.stationTree = stationtree
                }

                state.first = first


            }
        },
        setActiveThing(state, view) {
            if (view) {
                console.log("get active info------", view)
                if (view.info.Thing.is_station) {
                    return
                }
                state.activeThing = view
                let thingInfo = state.thingCache[view.tid]
                view.backInfo = thingInfo

                if (view.values) {
                    view.values.forEach(v => {
                        v.picktime = moment.unix(v.pick_time).format()
                    })

                }
                if (view.info.state == 'offline') {
                    view.oldValues = view.values
                    view.values = []
                }
                if (view.alarms) {
                    view.alarms.sort((a, b) => {
                        return a.time - b.time
                    })
                    view.alarms.forEach(alarm => {
                        alarm.alarm_time = moment.unix(alarm.time).format()
                    })
                }
                if (thingInfo) {
                    state.currentStationID = thingInfo.station_id
                }

            }
        }
    },
    actions: {
        refreshStations({ commit }, parentId) {
            if (!parentId) {
                parentId = ""
            }
            return new Promise((re, rej) => {
                if (parentId == "") {
                    getAll("tmodel").then(res => {
                        if (res && res.data && res.data.result) {
                            commit('setModels', res.data.result)
                        }
                    }).then(() => {
                        getChildren(re, rej, parentId, commit)
                    })
                } else {
                    getChildren(re, rej, parentId, commit)
                }
            })
        },
        refreshEdges({ commit }) {
            get("thing", "condition?model_id=IOTBASEmEdgeCTL").then((res => {
                if (res && res.data && res.data.result) {
                    commit('setEdges', res.data.result)
                }
            }))
        },
        saveThing({ commit }, item) {
            console.log("---------", commit)
            return new Promise((re, rej) => {
                update("/thing", item).then((res) => {
                    console.log("***************", res);
                    if (res && res.data && res.data.result) {
                        item.uid = res.data.result.uid;
                    }
                    let setParams = {
                        thing_id: item.uid,
                        values: item.params,
                    };

                    update("thingparam", setParams);
                    if (item.station) {
                        console.log(item);
                        update("/thingstation", {
                            thing_id: item.uid,
                            station_id: item.station.uid,
                        }).catch((err => {
                            rej(err)
                        }))
                            .then(() => {

                                re()

                                //let itemparams = item.params
                            })
                            .catch((err) => {
                                rej(err)
                            });
                    } else {
                        re()
                    }
                });
            })

        },

        refreshActiveThing({ state, commit, dispatch }, tid, his, isview) {
            console.log("refreshactive------------", tid)
            if (!tid) {
                if (!state.activeThing || !state.activeThing.tid) {
                    if (state.first) {
                        tid = state.first.uid
                        console.log("state.first------------", tid)
                    } else {
                        console.log("tid not found------------", tid)
                        return
                    }
                } else {
                    tid = state.activeThing.tid
                    console.log("user activething------------", tid)
                }


            }

            return new Promise((re, rej) => {
                getEx("data/view/" + tid).then((data) => {
                    if (data && data.data && data.data.result) {
                        if (!his) {
                            commit('setActiveThing', data.data.result)
                            re()
                        } else {
                            getOnlineState(tid).then(res => {
                                if (res && res.data && res.data.result) {
                                    data.data.result.stateHistory = res.data.result
                                }
                                commit('setActiveThing', data.data.result)
                            }).finally(() => {
                                re()
                            })
                        }

                    }
                }).catch((err) => {
                    console.log("error", err)
                    if (err?.error?.message == '设备不存在') {
                        if (state.first && tid == state.first.uid) {
                            state.first = null
                        }
                        if (state.activeThing.tid == tid) {
                            state.activeThing = null
                        }
                        err.noShow = true
                        dispatch('refreshAllThings', {})

                    }
                    state.first = null
                    rej(err.error)
                })
            })
        },

        refreshAllThings({ commit, state, dispatch }, { filterFun }) {


            return new Promise((re, rej) => {

                rawGet("api/extend/api/m_smartBoxForPolice?qmap[ctype]=thing_ex").then((res => {
                    if (res && res.data && res.data.result) {
                        commit('setThings', { res: res.data.result, filterFun })
                        let tid = ""
                        if (state.activeThing && state.activeThing.tid) {
                            //console.log("------------------------------",state.activeThing)
                            tid = state.activeThing.tid

                        } else {
                            tid = state?.first?.tid
                        }
                        if (tid == "") {
                            re()
                            //tid = 
                        }
                        else {
                            dispatch("refreshActiveThing", tid).finally(() => {
                                re()
                            })
                        }

                    }
                })).catch(err => {
                    rej(err)
                })
            })
        },
    }
}
